// 元素选择器模块
export const startElementPicker = async () => {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
    
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: () => {
        let currentHighlight = null
        
        // 生成智能选择器
        const generateSelector = (element) => {
          if (element.id) return `#${element.id}`
          
          if (element.className) {
            const classes = element.className.split(' ')
              .filter(c => c.trim() && !c.match(/^(active|hover|focus|selected)$/))
            if (classes.length > 0) return `.${classes[0]}`
          }
          
          const attrs = ['data-id', 'data-test', 'data-testid', 'name', 'role']
          for (const attr of attrs) {
            if (element.hasAttribute(attr)) {
              return `[${attr}="${element.getAttribute(attr)}"]`
            }
          }
          
          const parent = element.parentElement
          if (parent) {
            const siblings = Array.from(parent.children).filter(el => 
              el.tagName === element.tagName
            )
            if (siblings.length === 1) {
              const parentSelector = parent.id ? `#${parent.id}` : 
                                   parent.className ? `.${parent.className.split(' ')[0]}` : 
                                   parent.tagName.toLowerCase()
              return `${parentSelector} ${element.tagName.toLowerCase()}`
            } else {
              const index = siblings.indexOf(element) + 1
              return `${element.tagName.toLowerCase()}:nth-child(${index})`
            }
          }
          
          return element.tagName.toLowerCase()
        }
        
        const highlightElement = (element) => {
          if (currentHighlight) {
            currentHighlight.style.outline = ''
            currentHighlight.style.backgroundColor = ''
          }
          
          if (element && element !== document.body) {
            element.style.outline = '3px solid #ff4444'
            element.style.backgroundColor = 'rgba(255, 68, 68, 0.1)'
            currentHighlight = element
          }
        }
        
        const cleanup = () => {
          document.body.style.cursor = ''
          if (currentHighlight) {
            currentHighlight.style.outline = ''
            currentHighlight.style.backgroundColor = ''
          }
          document.removeEventListener('mouseover', handleMouseOver, true)
          document.removeEventListener('click', handleClick, true)
          document.removeEventListener('keydown', handleKeyDown, true)
        }
        
        const handleMouseOver = (e) => {
          e.preventDefault()
          highlightElement(e.target)
        }
        
        const handleClick = (e) => {
          e.preventDefault()
          e.stopPropagation()
          
          const selector = generateSelector(e.target)
          chrome.runtime.sendMessage({
            type: 'elementSelected',
            selector: selector
          })
          
          cleanup()
        }
        
        const handleKeyDown = (e) => {
          if (e.key === 'Escape') cleanup()
        }
        
        document.body.style.cursor = 'crosshair'
        document.addEventListener('mouseover', handleMouseOver, true)
        document.addEventListener('click', handleClick, true)
        document.addEventListener('keydown', handleKeyDown, true)
      }
    })
  } catch (error) {
    console.error('启动元素选择器失败:', error)
    alert('启动元素选择器失败，请确保已授权访问当前网站')
  }
}
